package com.ermaosk.juc.thread;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by admin
 * <p>
 * Date :2020/10/8
 * <p>
 * Description :
 * <p>
 * Version :1.0
 */
public class ThreadStop {
    private static final Logger logger = LoggerFactory.getLogger(ThreadStop.class);

    private static volatile boolean flag = false;



    public static void main(String[] args) {
//        stop();
//        interrupt2Stop();
        condition2Stop();
    }


    private static void stop() {
        Thread t1 = new Thread(() -> {
            logger.info("t1 starting...");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();

            }
            logger.info("t1 stopped...");
        }, "t1");

        t1.start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        logger.info("stop t1");

        t1.stop();
    }

    /**
     * 通过打断方式通知现场
     */
    private static void interrupt2Stop() {
        Thread t1 = new Thread(() -> {
            logger.info("t1 starting...");
            while(true){
                if(Thread.currentThread().isInterrupted()){
                    logger.info("t1 safe stopped...");
                    break;
                }
                try {
                    Thread.sleep(2000);
                    logger.info("t1 stopped...");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    //抛出异常后会重新设置中断标记为false，所以需要再次中断重置标记
                    Thread.currentThread().interrupt();
                }
            }

        }, "t1");

        t1.start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        logger.info("stop t1");

        t1.interrupt();
    }

    /**
     * 通过修改条件变量
     */
    private static void condition2Stop() {
        Thread t1 = new Thread(() -> {
            logger.info("t1 starting...");
            while(true) {
                if(flag){
                    logger.info("t1 safe stopped...");
                    break;
                }
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                logger.info("t1 stopped...");
            }

        }, "t1");

        t1.start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        logger.info("stop t1");

        flag = true;
    }

}
